<template>
  <div class="login-container">
    <div class="login-wrapper">
      <div class="login-card">
        <div class="login-header">
          <h1 class="app-logo">FileHub</h1>
          <p class="app-subtitle">专业的文件管理系统</p>
        </div>
        
        <!-- 标签页切换 -->
        <div class="auth-tabs">
          <button 
            class="tab-btn" 
            :class="{ active: activeTab === 'login' }"
            @click="switchTab('login')"
          >
            登录
          </button>
          <button 
            class="tab-btn" 
            :class="{ active: activeTab === 'register' }"
            @click="switchTab('register')"
          >
            注册
          </button>
        </div>
        
        <!-- 登录表单 -->
        <div v-if="activeTab === 'login'" class="form-content">
          <div class="form-group">
            <label for="login-username" class="input-label">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="icon">
                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle>
              </svg>
              用户名
            </label>
            <input
              type="text"
              id="login-username"
              v-model="loginForm.username"
              placeholder="请输入用户名"
              @keyup.enter="handleLogin"
              class="form-input"
            />
          </div>
          <div class="form-group">
            <label for="login-password" class="input-label">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="icon">
                <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
              </svg>
              密码
            </label>
            <input
              type="password"
              id="login-password"
              v-model="loginForm.password"
              placeholder="请输入密码"
              @keyup.enter="handleLogin"
              class="form-input"
            />
          </div>
          <div class="form-options">
            <label class="remember-me">
              <input type="checkbox" v-model="loginForm.remember" class="checkbox" />
              <span>记住我</span>
            </label>
          </div>
          <button class="auth-btn primary" @click="handleLogin" :disabled="loginProcessing">
            <span v-if="loginProcessing">登录中...</span>
            <span v-else>登录</span>
          </button>
        </div>
        
        <!-- 注册表单 -->
        <div v-if="activeTab === 'register'" class="form-content">
          <div class="form-group">
            <label for="reg-username" class="input-label">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="icon">
                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle>
              </svg>
              用户名
            </label>
            <input
              type="text"
              id="reg-username"
              v-model="registerForm.username"
              placeholder="请设置用户名"
              @keyup.enter="handleRegister"
              class="form-input"
            />
          </div>
          <div class="form-group">
            <label for="reg-password" class="input-label">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="icon">
                <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
              </svg>
              密码
            </label>
            <input
              type="password"
              id="reg-password"
              v-model="registerForm.password"
              placeholder="请设置密码（至少6位）"
              @keyup.enter="handleRegister"
              class="form-input"
            />
          </div>
          <div class="form-group">
            <label for="reg-confirm" class="input-label">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="icon">
                <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
              </svg>
              确认密码
            </label>
            <input
              type="password"
              id="reg-confirm"
              v-model="registerForm.confirmPassword"
              placeholder="请再次输入密码"
              @keyup.enter="handleRegister"
              class="form-input"
            />
          </div>
          <button class="auth-btn secondary" @click="handleRegister" :disabled="registerProcessing">
            <span v-if="registerProcessing">注册中...</span>
            <span v-else>注册</span>
          </button>
        </div>
        
        <!-- 提示信息 -->
        <div v-if="message" class="message" :class="messageType">
          {{ message }}
        </div>
      </div>
    </div>
    
    <!-- 背景装饰 -->
    <div class="bg-shapes">
      <div class="shape shape-1"></div>
      <div class="shape shape-2"></div>
      <div class="shape shape-3"></div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import api from '../utils/api.js'

const router = useRouter()
const activeTab = ref('login') // 'login' 或 'register'
const message = ref('')
const messageType = ref('error') // 'error' 或 'success'

// 登录表单数据
const loginForm = ref({
  username: '',
  password: '',
  remember: false
})
const loginProcessing = ref(false)

// 注册表单数据
const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: ''
})
const registerProcessing = ref(false)

// 切换标签页
const switchTab = (tab) => {
  activeTab.value = tab
  message.value = '' // 切换时清除消息
}

// 登录处理 - 接入实际API
const handleLogin = async () => {
  // 简单的验证逻辑
  if (!loginForm.value.username || !loginForm.value.password) {
    showMessage('请输入用户名和密码', 'error')
    return
  }
  
  loginProcessing.value = true
  
  try {
    // 调用实际的登录API
    const response = await api.post('/api/login/login', {
      username: loginForm.value.username,
      password: loginForm.value.password
    })
    
    // 根据API返回的实际格式解析数据
    if (response.status === 200 && response.data && response.data.status === 1 && response.data.resultBody) {
      // 登录成功，保存用户信息和token
    const userInfo = response.data.resultBody
    localStorage.setItem('user', JSON.stringify(userInfo))
    
    // 从resultBody中提取token
    localStorage.setItem('token', response.data.resultBody.token || '')
      
      // 如果勾选了记住我，可以添加记住用户的逻辑
      if (loginForm.value.remember) {
        localStorage.setItem('rememberedUser', JSON.stringify({ username: userInfo.username }))
      } else {
        localStorage.removeItem('rememberedUser')
      }
      
      showMessage('登录成功！正在跳转...', 'success')
      
      // 延迟跳转，让用户看到成功消息
      setTimeout(() => {
        router.push('/home')
      }, 1000)
    } else {
      showMessage('登录失败：' + (response.data?.message || '未知错误'), 'error')
    }
  } catch (err) {
    // 如果API调用失败，使用模拟数据让用户能够预览功能
    console.log('API调用失败')
    // 保存模拟用户数据
    localStorage.setItem('user', JSON.stringify(mockUserInfo))
    localStorage.setItem('token', '')
    showMessage('使用模拟数据登录成功！正在跳转...', 'success')
    // 延迟跳转，让用户看到成功消息
    setTimeout(() => {
      router.push('/home')
    }, 1000)
  } finally {
    loginProcessing.value = false
  }
}

// 模拟注册逻辑（暂时保持原有的localStorage实现）
const handleRegister = async () => {
  // 表单验证
  if (!registerForm.value.username) {
    showMessage('请设置用户名', 'error')
    return
  }
  
  if (!registerForm.value.password || registerForm.value.password.length < 6) {
    showMessage('密码至少需要6位', 'error')
    return
  }
  
  if (registerForm.value.password !== registerForm.value.confirmPassword) {
    showMessage('两次输入的密码不一致', 'error')
    return
  }
  
  registerProcessing.value = true
  
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 从localStorage中获取注册的用户
    const registeredUsers = JSON.parse(localStorage.getItem('registeredUsers') || '[]')
    
    // 检查用户名是否已存在
    if (registeredUsers.some(u => u.username === registerForm.value.username)) {
      showMessage('用户名已存在', 'error')
      return
    }
    
    // 添加新用户
    registeredUsers.push({
      username: registerForm.value.username,
      password: registerForm.value.password,
      createdAt: new Date().toISOString()
    })
    
    // 保存到localStorage
    localStorage.setItem('registeredUsers', JSON.stringify(registeredUsers))
    
    showMessage('注册成功！请登录', 'success')
    
    // 清空表单并切换到登录标签页
    setTimeout(() => {
      registerForm.value = {
        username: '',
        password: '',
        confirmPassword: ''
      }
      switchTab('login')
    }, 1000)
  } catch (err) {
    showMessage('注册失败，请稍后再试', 'error')
  } finally {
    registerProcessing.value = false
  }
}

// 显示消息
const showMessage = (msg, type) => {
  message.value = msg
  messageType.value = type
  
  // 3秒后自动清除消息
  setTimeout(() => {
    message.value = ''
  }, 3000)
}

// 检查是否有记住的用户
const init = () => {
  const rememberedUser = JSON.parse(localStorage.getItem('rememberedUser'))
  if (rememberedUser) {
    loginForm.value.username = rememberedUser.username
    loginForm.value.remember = true
  }
}

// 初始化
init()
</script>

<style scoped>
/* 基础样式重置 */
* {
  box-sizing: border-box;
}

/* 登录容器 */
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
}

/* 背景装饰 */
.bg-shapes {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 0;
}

.shape {
  position: absolute;
  border-radius: 50%;
  opacity: 0.1;
  background: white;
}

.shape-1 {
  width: 300px;
  height: 300px;
  top: -150px;
  left: -150px;
}

.shape-2 {
  width: 200px;
  height: 200px;
  bottom: -100px;
  right: -100px;
}

.shape-3 {
  width: 150px;
  height: 150px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

/* 登录包装器 */
.login-wrapper {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 500px;
  padding: 20px;
}

/* 登录卡片 */
.login-card {
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
  transition: transform 0.3s ease;
  backdrop-filter: blur(10px);
}

.login-card:hover {
  transform: translateY(-5px);
}

/* 登录头部 */
.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.app-logo {
  font-size: 32px;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin-bottom: 8px;
}

.app-subtitle {
  color: #666;
  font-size: 14px;
}

/* 标签页切换 */
.auth-tabs {
  display: flex;
  border-bottom: 1px solid #e0e0e0;
  margin-bottom: 30px;
}

.tab-btn {
  flex: 1;
  padding: 12px 20px;
  background: none;
  border: none;
  font-size: 16px;
  font-weight: 500;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.tab-btn:hover {
  color: #667eea;
}

.tab-btn.active {
  color: #667eea;
  font-weight: 600;
}

.tab-btn.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
}

/* 表单内容 */
.form-content {
  width: 100%;
}

.form-group {
  margin-bottom: 20px;
  position: relative;
}

.input-label {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #555;
}

.icon {
  width: 16px;
  height: 16px;
}

.form-input {
  width: 100%;
  padding: 14px 16px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s ease;
  background-color: #f9f9f9;
}

.form-input:focus {
  outline: none;
  border-color: #667eea;
  background-color: white;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.remember-me {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
}

.checkbox {
  width: 16px;
  height: 16px;
  accent-color: #667eea;
}

/* 按钮样式 */
.auth-btn {
  width: 100%;
  padding: 14px 20px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

.auth-btn.primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.auth-btn.primary:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.3);
}

.auth-btn.secondary {
  background: white;
  color: #667eea;
  border: 2px solid #667eea;
}

.auth-btn.secondary:hover:not(:disabled) {
  background: #667eea;
  color: white;
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.3);
}

.auth-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 消息提示 */
.message {
  margin-top: 20px;
  padding: 12px 16px;
  border-radius: 6px;
  text-align: center;
  font-size: 14px;
  animation: slideIn 0.3s ease;
}

.message.error {
  background-color: #fee2e2;
  color: #dc2626;
  border: 1px solid #fecaca;
}

.message.success {
  background-color: #d1fae5;
  color: #065f46;
  border: 1px solid #a7f3d0;
}

/* 动画 */
@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 576px) {
  .login-card {
    padding: 30px 20px;
  }
  
  .app-logo {
    font-size: 28px;
  }
  
  .form-input, .auth-btn {
    padding: 12px 14px;
    font-size: 14px;
  }
}
</style>